package com.base.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.SigningInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.IntRange;
import androidx.annotation.Nullable;

import com.base.app.BaseApp;
import com.loyal.core.helper.DeviceHelper;

import java.security.MessageDigest;
import java.util.List;

/**
 * @author loyal
 */
public class DevUtil extends DeviceHelper {
    /**
     * 获取进程
     */
    public static @Nullable String getProcessName(Context context) {
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
            if (runningApps == null) {
                return null;
            }
            for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
                if (proInfo.pid == android.os.Process.myPid()) {
                    if (proInfo.processName != null) {
                        return proInfo.processName;
                    }
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * 获得手机的唯一标识
     */
    public static String pdaSerialId() {
        try {
            String devId;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                devId = androidId();
            } else {
                String serial = serial();
                String mac = macAddress();
                final String unknownMac = "02:00:00:00:00:00";
                boolean macEmpty = TextUtils.isEmpty(mac) || unknownMac.equalsIgnoreCase(mac);
                devId = macEmpty ? serial : mac;
            }
            return devId + ":" + Build.MODEL + ":" + mobileType();
        } catch (Exception e) {
            return "";
        }
    }

    @SuppressLint("HardwareIds")
    public static String androidId() {
        Application app = BaseApp.getInstance();
        return Settings.Secure.getString(app.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    public static @Nullable String getSignatureMD5(Context context, String packageName) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName,
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? PackageManager.GET_SIGNING_CERTIFICATES : PackageManager.GET_SIGNATURES);

            if (null == packageInfo) return null;
            Signature[] signatures;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                SigningInfo signingInfo = packageInfo.signingInfo;
                signatures = null == signingInfo ? null : signingInfo.getApkContentsSigners();
            } else {
                signatures = packageInfo.signatures;
            }
            if (null == signatures || 0 == signatures.length)
                return null;

            byte[] input = signatures[0].toByteArray();
            byte[] digest = MessageDigest.getInstance("MD5").digest(input);

            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Get Mobile Type
     */
    public static String mobileType() {
        return Build.MANUFACTURER;
    }

    /**
     * 判断是手机还是平板等设备
     */
    public static boolean isTablet() {
        return (Resources.getSystem().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取最小宽度限制符尺寸
     */
    public static int smallWidth() {
        Configuration config = Resources.getSystem().getConfiguration();
        return config.smallestScreenWidthDp;
    }

    /**
     * 屏幕中间区域
     */
    public static Rect centerRectInScreen(@IntRange(from = 1) int widthRatio, @IntRange(from = 1) int heightRatio) {
        final Application application = BaseApp.getInstance();
        int screenWidth = getDisplayWidth(application);
        int screenHeight = getDisplayHeight(application);
        // 计算屏幕中央的位置
        int centerX = screenWidth / 2;
        int centerY = screenHeight / 2;

        // 定义中央区域的大小，这里以屏幕宽高的1/3为例，可以根据需要调整这个比例
        int centerRegionWidth = screenWidth / widthRatio;
        int centerRegionHeight = screenHeight / heightRatio;

        Rect rect = new Rect();
        rect.left = centerX - centerRegionWidth / 2;
        rect.right = centerX + centerRegionWidth / 2;
        rect.top = centerY - centerRegionHeight / 2;
        rect.bottom = centerY + centerRegionHeight / 2;
        return rect;
    }

    /**
     * @return [0]底盘顺时针旋转或者逆时针旋转
     * [1] 显示屏朝上转动还是朝下转动
     */
    public static int[] rectInCenter(Rect rect) {
        Log.e("rectInCenter", "faceRect: " + rect.flattenToString());

        // 计算Rect的中心点
        int rectCenterX = rect.centerX();
        Log.e("checkRectInCenter: ", "rectCenterX=" + rectCenterX);
        int rectCenterY = rect.centerY();
        Log.e("checkRectInCenter: ", "rectCenterY=" + rectCenterY);

        Rect centerRect = centerRectInScreen(4, 1);
        Log.e("rectInCenter", "centerRect: " + centerRect.flattenToString());

        int[] point = new int[]{0, 0};

        int xPoint = 0;//中间
        if (rectCenterX < centerRect.left) {
            xPoint = -1;//人脸居于屏幕左侧
        } else if (rectCenterX > centerRect.right) {
            xPoint = 1;//人脸居于屏幕右侧
        }
        int yPoint = 0;//中间
        if (rectCenterY < centerRect.top) {
            yPoint = -1;//人脸居于屏幕顶部
        } else if (rectCenterY > centerRect.bottom) {
            yPoint = 1;//人脸居于屏幕底部
        }
        point[0] = xPoint;
        point[1] = yPoint;

        return point;
    }
}
